package com.unsins.restlet;

import com.unsins.business.domain.system.ISysConstantRepository;
import com.unsins.business.domain.system.SysConstant;
import com.unsins.core.session.SessionManagerUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.Context;
import org.restlet.data.*;
import org.restlet.resource.*;

import java.util.logging.Logger;

/**
 * Created by IntelliJ IDEA.
 * User: odpsoft
 * Date: 2008-11-27
 * Time: 9:57:43
 * To change this template use File | Settings | File Templates.
 */
public class SysConstantResource extends Resource {
    private static final Logger logger = Logger.getLogger(SysConstantResource.class.getName());
    private ISysConstantRepository constantRepository;
    private String constantId;
    private SysConstant sysConstant;
    private com.unsins.business.jms.SpringProducer producer;

    public void setSysConstantRepository(ISysConstantRepository repository) {
        constantRepository = repository;
    }

    public void setSpringProducer(com.unsins.business.jms.SpringProducer pro) {
        producer = pro;
    }

    @Override
    public void init(Context context, Request request, Response response) {
        super.init(context, request, response);
        constantId = (String) request.getAttributes().get("constantid");
        sysConstant = null;

        //SessionManagerUtils.setSessionAttribute(request, constantId);
        getVariants().add(new Variant(MediaType.TEXT_PLAIN));
    }

    @Override
    public Representation represent(Variant variant) throws ResourceException {
        logger.info("start done sysconstant restlet!");
        sysConstant = constantRepository.get(new Long(constantId));
        JSONObject json = new JSONObject();
        try {
            producer.start();
        } catch (javax.jms.JMSException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        try {
            json.put("name", sysConstant.getListName());
            json.put("code", sysConstant.getListCode());
            json.put("id", sysConstant.getId());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return new StringRepresentation(json.toString(), MediaType.TEXT_PLAIN, Language.ALL, CharacterSet.UTF_8);
    }
}
